/*
 * OpennavMapProvider.cpp
 *
 *  Created on: 25.02.2011
 *      Author: Markus
 */

#include "OpennavMapServiceProvider.h"
#include "OpennavUtils.h"
#include "BadaImage.h"


OpennavMapServiceProvider::OpennavMapServiceProvider() : __pMap(null), __pRenderWorker(null), __pLock(null), __pListener(null), __kill(false), __render(false) {

}

OpennavMapServiceProvider::~OpennavMapServiceProvider() {
	if (__pRenderWorker != null) {
		__kill = true;
		__pRenderWorker->Join();
		delete __pRenderWorker;
		__pRenderWorker = null;
	}
	if (__pLock != null) {
		delete __pLock;
		__pLock = null;
	}
}

result OpennavMapServiceProvider::Construct(OpennavMap* map) {
	__pMap = map;
	__requestId = 0;
	__pRenderWorker = new Thread();
	__pRenderWorker->Construct(L"RenderWorker", *this, Thread::DEFAULT_STACK_SIZE, THREAD_PRIORITY_LOW);
	__pRenderWorker->Start();
	__pLock = new Mutex();
	__pLock->Create();
	return E_SUCCESS;
}

void OpennavMapServiceProvider::AddOpennavMapProviderListener(IOpennavMapProviderListener& listener) {
	__pListener = &listener;
}

int OpennavMapServiceProvider::RequestMap(Osp::Locations::Coordinates& mapCenter, float zoomLevel, float azimuth, int width, int height) {
	__pLock->Acquire();
	__mapCenter = mapCenter;
	__zoomLevel = zoomLevel;
	__azimuth = azimuth;
	__width = width;
	__height = height;
	__requestId++;
	__render = true;
	int currentRequestId = __requestId;
	AppLogDebug("map request %d", currentRequestId);
	__pLock->Release();
	return currentRequestId;
}

Osp::Base::Object* OpennavMapServiceProvider::Run(void) {
	AppLogDebug("render worker started");
	while(__kill == false) {
		if (__render) {
			AppLogDebug("render worker awakes");
			__pLock->Acquire();
			__render = false;
			int currentRequestId = __requestId;
			Osp::Locations::Coordinates center = __mapCenter;
			float zoomLevel = __zoomLevel;
			float azimuth = __azimuth;
			Osp::Graphics::Dimension size(__width, __height);
			currentRequestId = __requestId;
			__pLock->Release();
			if (__pListener != null) {
				OpennavMapSection* section = __pMap->CreateSection(center, zoomLevel, azimuth, size);
				__pListener->OnMapRequestFinished(section, currentRequestId);
			}
		} else {
			Thread::GetCurrentThread()->Sleep(0);
		}
	}
	AppLogDebug("render worker terminated");
	return null;
}

